package org.pblue.appengine.data.control;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.pblue.appengine.data.AppengineDataManager;
import org.pblue.appengine.data.bean.DataBean;


public class DeleteEntitiesServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;
  
  public static final String CALLBACK_PARAMETER = "callback";
  public static final String ENTITY_TYPE_PARAMETER = "type";
  
  @SuppressWarnings("unchecked")
  @Override
  protected void service(HttpServletRequest pReq, HttpServletResponse pRes) throws ServletException, IOException {
    String callback = pReq.getParameter(CALLBACK_PARAMETER);
    String type = pReq.getParameter(ENTITY_TYPE_PARAMETER);
    
    PersistenceManager pm = AppengineDataManager.getPersistenceManager();
    Query query = pm.newQuery("select from " + type);
    List<DataBean> dataBeans = (List<DataBean>) query.execute();
    
    for (DataBean dataBean : dataBeans) {
      pm.deletePersistent(dataBean);
    }
    
    pRes.getWriter().println("All " + type + " entities deleted.");
    
    if (callback != null && !callback.equals("")) {
      pRes.sendRedirect(callback);
    }
  }
  
}
